package com.example.piece.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.*
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.example.base.BaseApp
import com.example.base.aop.click.RepeatClick
import com.example.base.aop.permission.PermissionRequest
import com.example.base.broadcast.Event
import com.example.base.broadcast.EventBusUtil
import com.example.base.ext.getViewModel
import com.example.base.ext.navigationTo
import com.example.base.ext.toast
import com.example.base.tools.ConfigTool
import com.example.base.ui.activity.BaseActivity
import com.example.base.vm.onError
import com.example.piece.App
import com.example.piece.R
import com.example.piece.constant.Key
import com.example.piece.constant.RoutePath
import com.example.piece.databinding.ActivityLoginForPieceBinding
import com.example.piece.tools.SIMCardInfo
import com.example.piece.vm.UserViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kongzue.dialogx.DialogX
import com.kongzue.dialogx.dialogs.PopTip
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.kongzue.dialogx.style.MaterialStyle
import com.therouter.router.Route
import me.samlss.broccoli.Broccoli

@Suppress("UNUSED_PARAMETER")
@Route(path = RoutePath.MAIN_LOGIN_FOR_PIECE)
class LoginForPieceActivity : BaseActivity<ActivityLoginForPieceBinding>() {

    override val isTransparentStatusBar: Boolean = true

    override val isDarkMode: Boolean = true

    override fun getContentRes(): Int = R.layout.activity_login_for_piece

    var mBroccoli: Broccoli? = null

    private val userViewModel: UserViewModel by lazy {
        getViewModel<UserViewModel>()
    }


    override fun initData(savedInstanceState: Bundle?) {

        val m: WindowManager = windowManager
        val d: Display = m.getDefaultDisplay() // 为获取屏幕宽、高

        val p: WindowManager.LayoutParams = window.attributes // 获取对话框当前的参值

        p.height = ((d.getHeight() * 0.7).toInt()) // 高度设置为屏幕的1.0

        p.width = ((d.getWidth() * 1.0).toInt()) // 宽度设置为屏幕的0.8

        p.alpha = 1.0f // 设置本身透明度

        p.dimAmount = 0.8f // 设置黑暗度

        window.attributes = p // 设置生效

        window.setGravity(Gravity.BOTTOM) // 设置靠右对齐
//设置window属性(本例在onCreate函数中设置)
//触摸Dialog外区域时，外区域view接收触摸事件
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
//触摸Dialog外区域时通知Dialog触摸事件
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        DialogX.globalStyle = MaterialStyle.style()

        val spannableStringBuilder = SpannableStringBuilder()
        //设置文字
        spannableStringBuilder.append("登录/注册代表您同意《用户服务条款》\n和《隐私协议》")
        //设置文字点击事件（用户协议）
        spannableStringBuilder.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                navigationTo(
                    RoutePath.MAIN_H5_ACTIVITY, mutableMapOf(
                        Key.DataKey.H5_TITLE to "用户协议",

                        Key.DataKey.H5_URL to "https://res.villaday.com/static/pages/1907/19/190717-19.html"
                    )
                )
            }
        }, 10, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

        //设置文字点击事件（隐私协议）
        spannableStringBuilder.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                navigationTo(
                    RoutePath.MAIN_H5_ACTIVITY, mutableMapOf(
                        Key.DataKey.H5_TITLE to "隐私协议",
                        Key.DataKey.H5_URL to "https://res.villaday.com/static/pages/1907/19/190717-19.html"
                    )
                )
            }
        }, 20, 26, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        //设置颜色
        spannableStringBuilder.setSpan(
            ForegroundColorSpan(
                Color.parseColor(
                    "#46AFFF"
                )
            ), 10, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        spannableStringBuilder.setSpan(
            ForegroundColorSpan(
                Color.parseColor(
                    "#46AFFF"
                )
            ), 20, 26, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )


        mBinding.tvXieyi?.movementMethod = LinkMovementMethod.getInstance()
        mBinding.tvXieyi?.text = spannableStringBuilder
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event?.getAction() == MotionEvent.ACTION_OUTSIDE) {
            //接收到外部触摸事件时执行相应处理逻辑(本例中执行window消失机制)。
            finish();
            return true;
        }
        return super.onTouchEvent(event);
    }

    @RepeatClick
    fun getPhoneCode(view: View) {
        if (!mBinding.editUserName?.text.isNullOrEmpty()) {
            userViewModel.userLoginGetCode(
                this@LoginForPieceActivity,
                mBinding.editUserName?.text.toString()
            ) {
                toast(it.msg)
            } onError {
                toast(it)

            }
        } else {
            toast("请输入手机号码！")
        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
    @RepeatClick
    fun getPhoneNum(view: View) {
        getOwnPhone(mBinding.editUserName)


    }

    @RepeatClick
    fun loginByQQ(view: View) {

        if (!mBinding.editUserName?.text.isNullOrEmpty()) {
            userViewModel.userPswReset(
                this@LoginForPieceActivity,
                mBinding.editPassword?.text.toString(), "111sam111",
                mBinding.editUserName?.text.toString()
            ) {
                toast(it.msg)
            } onError {
                toast(it)

            }
        } else {
            toast("请输入手机号码！")
        }
    }

    @RepeatClick
    fun onSubmit(view: View) {
        if (!mBinding.editUserName?.text.isNullOrEmpty()) {
            if (!mBinding.editPassword?.text.isNullOrEmpty()) {
                userViewModel.userLoginCode(
                    this@LoginForPieceActivity,
                    mBinding.editPassword?.text.toString(),
                    mBinding.editUserName?.text.toString()
                ) {
                    if (it.code === 200) {
                        App.USER_TOKEN = it.data.token
                        BaseApp.USER_TOKEN1 = it.data.token
                        //存本地token
                        ConfigTool.putString(Key.DataKey.TOKEN,
                            it.data.token)
                        //登录成功
                        EventBusUtil.sendEvent(Event<Int>(Key.EventKey.EVENT_LOGIN))
                        LiveEventBus.get<Boolean>("login").post(true)
                        finish()
                    } else {
                        toast(it.msg)
                    }
                } onError {
                    toast(it)

                }
            } else {
                toast("请输入验证码！")

            }

        } else {
            toast("请输入手机号码！")
        }
    }

    //获取本机号码
    @SuppressLint("MissingPermission")
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
    @PermissionRequest(
        value = [
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_PHONE_NUMBERS,
            Manifest.permission.READ_SMS
        ]
    )

    fun getOwnPhone(phone: TextView?) {
        val phoneNumbers =
            SIMCardInfo(this@LoginForPieceActivity).phoneNumberS
        if (phoneNumbers.isNotEmpty()) {
            for (it in phoneNumbers) {

            }
            phone?.text = phoneNumbers[0]

        } else {
            toast("暂未获取到手机号")
        }


    }


}